/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package control;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import model.Category;
import model.Course;
import model.Teacher;
import org.hibernate.Transaction;
import org.hibernate.Session;
import org.hibernate.SessionFactory;

/**
 *
 * @author Vince
 */
public class CourseManager extends HttpServlet {

    /** 
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        SessionFactory sessionFactory = SchoolContentManager.sessionFactory;
        Session session = sessionFactory.getCurrentSession(); //get the session from the sessionFactory
        Transaction transaction = session.beginTransaction(); //start the transaction
        HttpSession sessie = request.getSession();
        boolean delete = false;
        Category category = null;
        Course course = null;
        Teacher teacher;
        String reqp=request.getParameter( "p" );
        Object sesp=sessie.getAttribute( "courseManager" );
        if(reqp==null){
            reqp="";
        }else{
            sesp="";
        }
        if(sesp==null){
            sesp="";
        }
        //System.out.println("nullpointer" + sesp);
        if (reqp.equals("createCategory")||sesp.equals("createCategory")) {
            if (request.getParameter("categoryName").isEmpty() || request.getParameter("categoryDescription").isEmpty()) { //check if everything is filled in
                sessie.setAttribute("createCategoryError", "<b>One or more fields have not been filled in!</b>");
                sessie.setAttribute("contentPage", "/createCategory.jsp");
            } else {
                String getCategorySQL = "SELECT * FROM Category C WHERE C.category_name = '" + request.getParameter("categoryName") + "'";
                ArrayList<Category> categories = (ArrayList) session.createSQLQuery(getCategorySQL).list(); //Get all category information by category name

                Iterator it = categories.iterator();
                if (!it.hasNext()) {
                    category = new Category();
                    category.setCategoryName(request.getParameter("categoryName")); //set the values of the category to given values
                    category.setCategoryDescription(request.getParameter("categoryDescription"));
                    sessie.setAttribute("createCategoryError", "<b>Category " + category.getCategoryName() + " successfully created!</b>");
                    sessie.setAttribute("category", category.getCategoryName());
                    sessie.setAttribute("contentPage", "createCategory.jsp");
                }
            }
            response.sendRedirect("index");
        }

        if (reqp.equals("createCourse")||sesp.equals("createCourse")) {
            if (request.getParameter("cName").isEmpty() || request.getParameter("cDescription").isEmpty()) { //check if everything is filled in
                sessie.setAttribute("createCourseError", "<b>One or more fields are empty!</b>");
                sessie.setAttribute("contentPage", "/createCategory.jsp");
            } else {
                String getCourseSQL = "SELECT * FROM Course C WHERE C.cName = '" + request.getParameter("courseName") + "'";
                String getTeachersSQL = "SELECT * FROM Gebruiker G WHERE G.ucode IN (SELECT T.ucode FROM teacher T)";
                ArrayList<Object[]> teachers = (ArrayList) session.createSQLQuery(getTeachersSQL).list();
                ArrayList<Course> courses = (ArrayList) session.createSQLQuery(getCourseSQL).list(); //Get all course information by course name

                Iterator it = courses.iterator();
                if (!it.hasNext()) {
                    category = new Category();
                    course = new Course();
                    teacher = new Teacher();
                    category = (Category) session.get(Category.class, request.getParameter("category"));
                    Iterator it2 = teachers.iterator();
                    teacher = null;
                    if (it2.hasNext()) {
                        teacher = (Teacher) session.get(Teacher.class, (String)((Object[])it2.next())[0]);

                    }
                    course.setCategory(category);
                    course.setcName(request.getParameter("cName")); //set the values of the course to given values
                    course.setcDescription(request.getParameter("cDescription"));
                    course.setTeacher(teacher);
                    sessie.setAttribute("createCourseError", "<b>Course " + course.getcName() + " successfully created!</b>");
                    sessie.setAttribute("course", course.getcName());
                    sessie.setAttribute("teachers", teachers);
                    sessie.setAttribute("contentPage", "createCourse.jsp");
                }
            }
            response.sendRedirect("index");
        }

        if (reqp.equals("deleteCategory")||sesp.equals("deleteCategory")) {
            category = (Category) session.get(Category.class, request.getParameter("category"));
            String ifCategoryUsedSQL = "SELECT * FROM Course C WHERE C.category_category_name ='" + request.getParameter("category") + "'";
            ArrayList<Object[]> categoryList = (ArrayList) session.createSQLQuery(ifCategoryUsedSQL).list();
            if (!categoryList.isEmpty()) {
                category = null;
                sessie.setAttribute("deleteCategoryMessage", "<b>Category '" + request.getParameter("category") + "' can not be deleted while being used by a course!</b>");
            } else {
                delete = true;
                sessie.setAttribute("deleteCategoryMessage", "<b>Category '" + request.getParameter("category") + "' successfully deleted!</b>");
            }
            String getCategoryNameSQL = "SELECT C.category_name FROM Category C";
            ArrayList<Category> categories = (ArrayList) session.createSQLQuery(getCategoryNameSQL).list();
            sessie.setAttribute("categories", categories);
            sessie.setAttribute("contentPage", "deleteCategory.jsp");
            addHistori(sessie, "/courseManager.jsp");

            response.sendRedirect("index");
        }

        if (reqp.equals("deleteCourse")||sesp.equals("deleteCourse")) {
            course = (Course) session.get(Course.class, request.getParameter("course"));
            delete = true;
            String getCourseNameSQL = "SELECT C.cName FROM Course C";
            ArrayList<Course> courses = (ArrayList) session.createSQLQuery(getCourseNameSQL).list();
            sessie.setAttribute("courses", courses);
            sessie.setAttribute("deleteCourseMessage", "<b>Course '" + request.getParameter("course") + "' successfully deleted!</b>");
            sessie.setAttribute("contentPage", "courseManager.jsp");

            response.sendRedirect("index");
        }

        if (reqp.equals("editCategorySelect")||sesp.equals("editCategorySelect")) {
            String getCategoryNameSQL = "SELECT C.category_name FROM Category C WHERE C.category_name ='" + request.getParameter("category") + "'";
            String getCategoryDescriptionSQL = "SELECT C.category_description FROM Category C WHERE C.category_name ='" + request.getParameter("category") + "'";
            ArrayList<String> categoryName = (ArrayList) session.createSQLQuery(getCategoryNameSQL).list();
            ArrayList<String> categoryDescription = (ArrayList) session.createSQLQuery(getCategoryDescriptionSQL).list();

            sessie.setAttribute("categoryNameView", categoryName.get(0));
            sessie.setAttribute("categoryName", categoryName.get(0));
            sessie.setAttribute("categoryDescription", categoryDescription.get(0));
            sessie.setAttribute("contentPage", "editCategory.jsp");
            addHistori(sessie, "/courseManager.jsp");

            response.sendRedirect("index");
        }

        if (reqp.equals("editCategory")||sesp.equals("editCategory")) {
            if (request.getParameter("categoryDescription").isEmpty()) { //check if everything is filled in
                sessie.setAttribute("editCategoryMessage", "<b>One or more fields are empty!</b>");
                sessie.setAttribute("contentPage", "/editCategory.jsp");
                response.sendRedirect("index");
            } else {
                category = (Category) session.get(Category.class, request.getParameter("categoryName"));
                category.setCategoryDescription(request.getParameter("categoryDescription"));

                sessie.setAttribute("editCategoryMessage", "<b>Change Succesful!</b>");
                sessie.setAttribute("categoryName", request.getParameter("categoryName"));
                sessie.setAttribute("categoryNameView", request.getParameter("categoryName"));
                sessie.setAttribute("categoryDescription", request.getParameter("categoryDescription"));
                sessie.setAttribute("contentPage", "editCategory.jsp");
                addHistori(sessie, "/courseManager.jsp");

                response.sendRedirect("index");
            }
        }

        if (reqp.equals("editCourseSelect")||sesp.equals("editCourseSelect")) {
            String getCourseNameSQL = "SELECT C.cName FROM Course C WHERE C.cName ='" + request.getParameter("courses") + "'";
            String getCourseDescriptionSQL = "SELECT C.cdescription FROM Course C WHERE C.cName ='" + request.getParameter("courses") + "'";
            String getCourseCategoryNameSQL = "SELECT C.category_category_name FROM Course C WHERE C.cName ='" + request.getParameter("courses") + "'";
            String getCourseTeacherNameSQL = "SELECT * FROM Gebruiker G WHERE G.ucode IN (SELECT C.teacher_ucode FROM Course C WHERE C.cName ='" + request.getParameter("courses") + "')";
            String getCategoryNameSQL = "SELECT C.category_name FROM Category C WHERE c.category_name NOT IN (SELECT Co.category_category_name FROM Course Co WHERE Co.cName ='" + request.getParameter("courses") + "')";
            String getTeachersSQL = "SELECT * FROM Gebruiker G WHERE G.ucode IN (SELECT T.ucode FROM teacher T) AND G.firstname NOT IN (SELECT G2.firstname FROM Gebruiker G2 WHERE G2.ucode IN (SELECT C.teacher_ucode FROM Course C WHERE C.cName ='" + request.getParameter("courses") + "'))";
            ArrayList<String> courseName = (ArrayList) session.createSQLQuery(getCourseNameSQL).list();
            ArrayList<String> courseDescription = (ArrayList) session.createSQLQuery(getCourseDescriptionSQL).list();
            ArrayList<String> courseCategoryName = (ArrayList) session.createSQLQuery(getCourseCategoryNameSQL).list();
            ArrayList<Object[]> courseTeacherName = (ArrayList) session.createSQLQuery(getCourseTeacherNameSQL).list();
            ArrayList<String> categories = (ArrayList) session.createSQLQuery(getCategoryNameSQL).list();
            ArrayList<Object[]> teachers = (ArrayList) session.createSQLQuery(getTeachersSQL).list();

            if (courseTeacherName.isEmpty()) {
                courseTeacherName.add(0, null);
            }

            sessie.setAttribute("courseNameView", courseName.get(0));
            sessie.setAttribute("courseName", courseName.get(0));
            sessie.setAttribute("courseDescription", courseDescription.get(0));
            sessie.setAttribute("courseCategoryName", courseCategoryName.get(0));
            sessie.setAttribute("courseTeacherName", courseTeacherName.get(0));
            sessie.setAttribute("categories", categories);
            sessie.setAttribute("teachers", teachers);
            sessie.setAttribute("contentPage", "editCourse.jsp");
            addHistori(sessie, "/courseManager.jsp");

            response.sendRedirect("index");
        }

        if (reqp.equals("editCourse")||sesp.equals("editCourse")) {
            if (request.getParameter("courseDescription").isEmpty()) { //check if everything is filled in
                sessie.setAttribute("editCourseMessage", "<b>A course requires a description!</b>");
                sessie.setAttribute("contentPage", "/editCourse.jsp");
                response.sendRedirect("index");
            } else {
                String getCategoryNameSQL = "SELECT C.category_name FROM Category C WHERE c.category_name NOT IN (SELECT Co.category_category_name FROM Course Co WHERE Co.cName ='" + request.getParameter("courseName") + "')";
                String getTeachersSQL = "SELECT * FROM Gebruiker G WHERE G.ucode IN (SELECT T.ucode FROM teacher T) AND G.firstname NOT IN (SELECT G2.firstname FROM Gebruiker G2 WHERE G2.ucode IN (SELECT C.teacher_ucode FROM Course C WHERE C.cName ='" + request.getParameter("courses") + "'))";
                System.out.println("ucodeucodeucodeucodeucodeucodeucodeucodeucodeucode" + request.getParameter("teachers"));
                String getTeacherSQL = "SELECT T.ucode FROM Teacher T WHERE T.ucode = '" + request.getParameter("teachers") + "'";
                String getCourseTeacherNameSQL = "SELECT * FROM Gebruiker G WHERE G.ucode = '" + request.getParameter("teachers") + "'";

                course = (Course) session.get(Course.class, request.getParameter("courseName"));
                category = (Category) session.get(Category.class, request.getParameter("categories"));
                ArrayList<Object[]> eteacher = (ArrayList) session.createSQLQuery(getTeacherSQL).list(); //Get all information from user by using email and password
                Iterator it = eteacher.iterator();
                teacher = null;
                if (it.hasNext()) {
                    teacher = (Teacher) session.get(Teacher.class, (String) it.next());

                }
                

                course.setcDescription(request.getParameter("courseDescription"));
                course.setCategory(category);
                course.setTeacher(teacher);// werkt nog niet.
                session.saveOrUpdate(course);

                ArrayList<String> categories = (ArrayList) session.createSQLQuery(getCategoryNameSQL).list();
                ArrayList<Object[]> teachers = (ArrayList) session.createSQLQuery(getTeachersSQL).list();
                ArrayList<Object[]> courseTeacherName = (ArrayList) session.createSQLQuery(getCourseTeacherNameSQL).list();
            
                sessie.setAttribute("editCourseMessage", "<b>Change Succesful!</b>");
                sessie.setAttribute("courseNameView", request.getParameter("courseName"));
                sessie.setAttribute("courseName", request.getParameter("courseName"));
                sessie.setAttribute("courseDescription", request.getParameter("courseDescription"));
                sessie.setAttribute("courseCategoryName", request.getParameter("categories"));
                sessie.setAttribute("courseTeacherName", courseTeacherName.get(0));
                sessie.setAttribute("categories", categories);
                sessie.setAttribute("teachers", teachers);
                sessie.setAttribute("contentPage", "editCourse.jsp");
                addHistori(sessie, "/courseManager.jsp");

                response.sendRedirect("index");
            }
        }

        if (reqp.equals("selectCourseCategory")||sesp.equals("selectCourseCategory")) {
            String getCourseSQL = "SELECT C.cName FROM Course C WHERE C.category_category_name ='" + request.getParameter("category") + "'";
            ArrayList<String> courses = (ArrayList) session.createSQLQuery(getCourseSQL).list();

            sessie.setAttribute("courses", courses);

            sessie.setAttribute("contentPage", "CourseCatalogue.jsp");

            response.sendRedirect("index");
        }

        if (reqp.equals("viewCourse")||sesp.equals("viewCourse")) {
            course = (Course) session.get(Course.class, request.getParameter("selectedCourse"));
            String getFileNameByCategorySQL = "SELECT F.fName FROM File F WHERE F.fCourse ='" + request.getParameter("selectedCourse") + "'";
            String getFileDataByCategorySQL = "SELECT F.fLocation FROM File F WHERE F.fCourse ='" + request.getParameter("selectedCourse") + "' AND F.isAnswer = FALSE";
            String getAnswerDataByCategorySQL = "SELECT F.fLocation FROM File F WHERE F.fCourse ='"+ request.getParameter("selectedCourse") +"' AND F.isAnswer = TRUE";
            String getOwnAnswerByCategorySQL = "SELECT F.fLocation FROM File F WHERE F.fCourse ='"+ request.getParameter("selectedCourse") +"' AND F.isAnswer = TRUE AND F.getName = '"+request.getParameter("usernamehaha")+"'";
            System.out.println("Ik krijg terug: " + request.getParameter("selectedCourse"));
            ArrayList<String> filenames = (ArrayList) session.createSQLQuery(getFileNameByCategorySQL).list();
            ArrayList<String> files = (ArrayList) session.createSQLQuery(getFileDataByCategorySQL).list();
            ArrayList<String> answers = (ArrayList) session.createSQLQuery(getAnswerDataByCategorySQL).list();
            ArrayList<String> ownAnswers = (ArrayList) session.createSQLQuery(getOwnAnswerByCategorySQL).list();
            sessie.setAttribute("fileByCategory", files);
            sessie.setAttribute("answerByCategory", answers);
            sessie.setAttribute("courseName", course.getcName());
            sessie.setAttribute("courseDescription", course.getcDescription());
            sessie.setAttribute("courseTeacher", course.getTeacher().getFirstName().toString());
            sessie.setAttribute("contentPage", "viewCourse.jsp");
            addHistori(sessie, "/selectCourseCategory.jsp");

            response.sendRedirect("index");
        }

        if (course != null) {
            if (delete == true) {
                session.delete(course);
            } else {
                session.saveOrUpdate(course); //save new category
            }
        }

        if (category != null) {
            if (delete == true) {
                session.delete(category);
            } else {
                session.saveOrUpdate(category); //save new category
            }
        }

        transaction.commit(); //commit category to data
    }

    private void addHistori(HttpSession sessie, Object attribute) {
        List<Object> historie;
        if (sessie.getAttribute("lastpage") == null) {
            historie = new ArrayList();
        } else {
            historie = (ArrayList<Object>) sessie.getAttribute("lastpage");
        }
        System.out.println("terug naar" + attribute);
        historie.add(attribute);

        sessie.setAttribute("lastpage", historie);
    }

    private Object getLast(HttpSession sessie) {
        List<Object> historie = (List<Object>) sessie.getAttribute("lastpage");
        Object re = historie.get(historie.size() - 1);
        historie.remove(re);
        return re;
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /** 
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}
